/*
	后台页面控制器
*/
'use strict';
var moment	= require('moment');
var AV 			= require('leanengine');
var os 			= require('os');
var fs 			= require('fs');
let admin		= {};
var avImage 		= AV.Object.extend("Image");
var avSysConfig = AV.Object.extend("SysConfig");

/**
 * 后台登录页面
 * 2015.04.18  by 胡斌
 */
admin.loginPage = function(req,res) {
	var error=req.query.error;
	//console.log("loginPage:"+error);
	if(req.AV.user) return res.redirect('/admin/index');
  res.render('admin-login',{error:error});
}

/**
 * 后台索引页面
 * 2015.04.18  by 胡斌
 */
admin.indexPage = function(req, res) {
	//console.log(process.env.Test);

	res.render('admin-index.html',{
		user:req.AV.user
	});
}

/**
 * 后台图片上传
 * 2015.04.18  by 胡斌
 */
admin.doUploadImage = function(req,res,next){
	//console.dir(req.AV);
	if(req.busboy){
		var base64data = [];
    var pubFileName = '';
    var pubMimeType = '';
    req.busboy.on('file',(fieldname, file, fileName, encoding, mimeType) => {
      var buffer = '';
      pubFileName = fileName;
      pubMimeType = mimeType;
			if(pubMimeType.indexOf('image/')>-1){
				file.setEncoding('base64');
	      file.on('data', function(data) {
	        buffer += data;
	      }).on('end', function() {
	        base64data.push(buffer);
	      });
			}
    }).on('finish', function() {
			if(pubMimeType.indexOf('image/')>-1){
      	var f = new AV.File(pubFileName, {base64: base64data[0]});
				try {
	        f.save().then(function(fileObj) {
						var image=new avImage();
						image.set("file",fileObj);
						image.set("user",req.AV.user);
						image.set("isSys",true);
						return image.save();
	        }).then(function(image){
						//console.log(image.get("user"));
						res.json({success:true,id:image.id,file_path:"/p?w=800&id="+image.id});
					}, function(error) {
						console.error(error.message);
						res.json({success:false,msg:"上传失败！"});
					});
	      }catch (err) {
	        console.error('uploadFile - ' + err);
	        res.status(502);
	      }
			}else{
				res.json({success:false,msg:"上传失败，未获取到文件，或文件格式不正确！"});
			}
    })
    req.pipe(req.busboy);
	}else{
    console.error('uploadFile - busboy undefined.');
    res.status(502);
  }
}


/**
 * 统计数据
 * 2016.05.05  by 胡斌
 */
admin.ajaxCount = function(req, res) {
	var date=moment().startOf('day').toISOString();
	/*AV.Promise.when(
	  AV.Query.doCloudQuery("select count(*) from Image where isSys=false and  createdAt > date('"+date+"')"),
	  AV.Query.doCloudQuery("select count(*) from Trip where createdAt > date('"+date+"')"),
	  AV.Query.doCloudQuery("select count(*) from _User where createdAt > date('"+date+"')"),
	  AV.Query.doCloudQuery("select count(*) from ReportLog where state=0")
	).then(function (r1, r2, r3, r4) {
	  res.json({image:r1.count,trip:r2.count,user:r3.count,report:r4.count});
	});*/
}

/**
 * 后台登录
 * 2015.04.18  by 胡斌
 */
admin.doLogin = function(req,res) {
	//console.log(req.body.email);
	AV.User.logIn(req.body.username,req.body.password).then(function(user) {
			//console.log(user.get("username"));
			res.saveCurrentUser(user);
			//跳转到profile页面。
			res.redirect('/admin/index');
	},function(error) {
		if(typeof(error)=="object"){error=error.message;}
		console.error(error);
		//登录失败，跳转到登录页面
		res.redirect('/admin-login?error='+error);
	});
}

/**
 * 后台登出
 * 2015.04.18  by 胡斌
 */
admin.doLogout = function(req,res) {
	//AV.User.logOut();
	//console.log("doLogout");
	var user = req.currentUser;
	user.logOut();
	res.clearCurrentUser();
  res.redirect('/admin-login');
}

/**
 * 后台登录页面
 * 2015.04.18  by 胡斌
 */
admin.doCkAuth = function(req,res,next) {
	//console.log(req.AV.user);
	if(!req.AV.user){// 判断用户是否已经登录
		res.redirect('/admin-login');
		return false;
	}else if(req.AV.user.get("adminRole")!="admin"){
		res.redirect('/admin-logout');
		return false;
	}else{
		res.saveCurrentUser(req.AV.user);
	}
	next();
}


/**
 * 初始化系统
 * 2016.06.30  by 胡斌
 */
admin.doSysInit = function(req,res,next) {
	var querySysConfig 	= new AV.Query(avSysConfig);
	querySysConfig.count().then(function(count){
		if(count==0){
			var promises = [];

			var	val=["上衣","T恤衫","衬衫","连衣裙","半裙","裤子","背带裤","套装","爬爬服"];

			var lotterySysConfig=new avSysConfig();
			lotterySysConfig.set("type","data");
			lotterySysConfig.set("name","type");
			lotterySysConfig.set("value",val);

			promises.push(lotterySysConfig.save());

			var	val2=["Amaia","Babidu","Dotty Dungarees","Hucklebones","Lucien Zazou","Marmar Copenhagen","Mayoral","Rachel Riley"];
			var newSysConfig=new avSysConfig();
			newSysConfig.set("type","data");
			newSysConfig.set("name","brand");
			newSysConfig.set("value",val2);
			promises.push(newSysConfig.save());

			var	val3=["新生儿","3个月","6个月","9个月","12个月","18个月","24个月/2岁","3岁","4岁","5岁","6岁+","均码"];
			var newSysConfig2=new avSysConfig();
			newSysConfig2.set("type","data");
			newSysConfig2.set("name","size");
			newSysConfig2.set("value",val3);
			promises.push(newSysConfig2.save());

			return AV.Promise.when(promises);
		}else{
			return AV.Promise.as(true);
		}
	}).then(function(result){
		if(typeof(result)!="boolean")console.log("Init successed!");
	},function(errors){
		res.json(errors);
		return false;
	});
	next();
}
module.exports = admin;
